<?php
// $Id: listing_location_handler_sort_location_distance.inc,v 1.1 2010/12/04 00:43:47 newzeal Exp $

/**
 * @file
 * Coordinates sort handler.
 */

class listing_location_handler_sort_location_distance extends views_handler_sort {

  function query() {

    $location = listing_location_calculate_coords();
    $this->ensure_my_table();

    // OK, so this part will need a little explanation.
    // Since the distance calculation is so icky, we try quite hard
    // to save some work for the database.
    // If someone has added a field that matches the sort, we just sort on that column!
    $alias = $this->table_alias .'_'. $this->field .'_sort';
    foreach ($this->view->field as $k => $v) {
      if ($v->table == 'location' && $v->field == 'distance' && $v->options['relationship'] == $this->options['relationship']) {
        if ($v->options['origin'] == $this->options['origin']
            && $v->options['units'] == $this->options['units']
            && $v->options['latitude'] == $this->options['latitude']
            && $v->options['longitude'] == $this->options['longitude']) {
          // We have a match! Sync aliases to make it easier on the database.
          $alias = $v->field_alias;
        }
      }
    }
//drupal_set_message('lat '.$location['latitude']);
    if (empty($location['latitude']) && empty($location['longitude'])) {
      // We don't know the distance.
      // Therefore, we don't need to sort on it.
    }
    else {
      // This is done exactly the same as the field version.
      // Views is ok with us redefining the formula for a field.
      // If ANYTHING differs in the configuration, we will use a new alias.
      $this->query->add_orderby(NULL, earth_distance_sql($location['longitude'], $location['latitude'], $this->table_alias), $this->options['order'], $alias);
    }
  }
}
